package com.soft.hwx.scdapp.socket;

import android.util.Log;

import com.soft.hwx.logutillib.LogUtil;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.LinkedList;

public class UdpHelper implements Runnable {
    public    Boolean IsThreadDisable = false;//指示监听线程是否终止
    public static final String DEST_IP = "127.0.0.1";
    public    Integer localServerPort = 8080;   // 安卓端UDP服务器监听的端口 这是默认端口  具体设置在AppConfig里面
    private      DatagramSocket datagramSocket = null;
    private   Integer dstPort=0;
    private    String dstIp;
    private   int type=0;


    private static final int UPD_SERVER_HELP = 0;     //供应商id
    private static final int UPD_CLIENT_HELP = 1;    //产品id

    private  UdpRecvInterface recvInterface = null;


    private LinkedList<SBuf> bufList = new LinkedList();
    private  Object bufListLock = new Object();


    /*
        UDP SERVER
     */
    public UdpHelper(Integer port,UdpRecvInterface recvInterface){
        if(port != null)
             localServerPort = port;
        this.recvInterface = recvInterface;
        type = UPD_SERVER_HELP;
    }

    /*
        UDP CLIENT
     */
    public UdpHelper(String dstIP,int dstPort){
        this.dstPort = dstPort;
        this.dstIp = dstIP;
        type = UPD_CLIENT_HELP;
    }

    public  void SetListenPort(Integer port){
        localServerPort = port;
    }

    public  void SetRecvInterface(UdpRecvInterface recvInterface){
        this.recvInterface = recvInterface;
    }

    public  void CloseListen(){
        if(datagramSocket!=null){
            datagramSocket.close();
        }
    }

    public  void ReStartListen(Integer port){

        SetListenPort(port);
        CloseListen();
    }

    public void StartListen()  {

        // 接收的字节大小，客户端发送的数据不能超过这个大小
        byte[] message = new byte[1024];

        DatagramPacket datagramPacket = new DatagramPacket(message,
                message.length);

        while(!IsThreadDisable) {


            if(datagramSocket==null){
                try {
                    Log.d("UdpHelper", "创建服务器，监听端口:"+String.valueOf(localServerPort));
                    //datagramSocket = new DatagramSocket(localServerPort,InetAddress.getByName(DEST_IP));
                    datagramSocket = new DatagramSocket(localServerPort);
                } catch (IOException e) {//IOException
                    LogUtil.d("创建服务器 失败!!");
                    Log.d("UdpHelper","创建服务器 失败");
                    e.printStackTrace();
                    break;
                }
            }

            try {
                while (!IsThreadDisable) {
                    // 准备接收数据
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    String date = df.format(new java.util.Date());
                    Log.d("UdpHelper", date+"准备接受");
                    datagramSocket.receive(datagramPacket);
                    /*
                    String strMsg=new String(datagramPacket.getData()).trim();
                    Log.d("UdpHelper", datagramPacket.getAddress()
                            .getHostAddress().toString()
                            + ":" +strMsg );*/
                    //放入处理线程
                    //放入回调
                    if(recvInterface!=null)
                        recvInterface.Recv(datagramPacket.getData(),datagramPacket.getLength());

                }
            } catch (IOException e) {//IOException
                Log.d("UdpHelper","udp server close or other error rebulid server");
                e.printStackTrace();
            }

            //判断是否关闭
           if( datagramSocket.isClosed())
               datagramSocket.close();

            //重置socket
            datagramSocket = null;
        }
    }
    /*
               MainActivity 可以不调用
        */
    public  int send(String dstIp,Integer dstPort,byte[] buf,int dataSize){

        try {
            DatagramSocket socket = new DatagramSocket();
            socket.connect(new InetSocketAddress(dstIp, dstPort));

            DatagramPacket dp = new DatagramPacket(buf,dataSize);
            socket.send(dp);

            return 0;
        } catch (IOException e) {
            Log.d("UdpHelper","udp client send faild:"+e.getMessage());
            e.printStackTrace();

            return -1;
        }
    }

    /*
            MainActivity 可以调用
     */
    public  int send2(byte[] buf,int dataSize){
        synchronized(bufListLock) {
            Log.d("UdpHelper", "发送命令");
            bufList.addLast(new SBuf(buf,dataSize));
            bufListLock.notify();
        }

        return 0;
    }


    private void sBufProcThread(){
        DatagramSocket socket = null;

        try {
            Log.d("UdpHelper","创建 udp 发送 socket");
            socket = new DatagramSocket();
            Log.d("UdpHelper","dstip:"+this.dstIp);
            Log.d("UdpHelper","dstPort:"+String.valueOf(this.dstPort));
            socket.connect(new InetSocketAddress(this.dstIp, this.dstPort));
        } catch (IOException e) {
            Log.d("UdpHelper","udp client send faild:"+e.getMessage());
            e.printStackTrace();
        }


        while (!IsThreadDisable) {
            if (bufList.size() <= 0) {
                try {
                    //主线程等待通过notify() 唤醒
                    //临界区  保护队列
                    synchronized (bufListLock) {
                        bufListLock.wait();
                    }
                } catch (Exception e) {

                }
            }

            if (bufList.size() <= 0) {
                continue;
            }

            SBuf buf = null;
            //临界区  保护队列
            synchronized (bufListLock) {
                buf = bufList.getFirst();
                bufList.removeFirst();
            }

            if (buf == null)
                continue;

            //解析消息
            try {
               // send(config.hostIp,config.hostPort,msg.getBytes("UTF-8"));
                DatagramPacket dp = new DatagramPacket(buf.buf,buf.dataSize);
                //Log.d("UdpHelper", "发送消息:"+String.valueOf((byte[])buf.buf));
                //System.out.println(Arrays.toString(buf.buf));
                socket.send(dp);
            } catch (IOException ioe) {
            }
        }
    }

    public static String getIP(){

        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address))
                    {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }
        catch (SocketException ex){
            ex.printStackTrace();
        }
        return null;
    }

    //获取设备外网地址
    public static String GetNetIp() {
        String IP = "";
        try {
            String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
            URL url = new URL(address);

            //  URLConnection htpurl=url.openConnection();

            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"); //设置浏览器ua 保证不出现503

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream in = connection.getInputStream();

                // 将流转化为字符串
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in));

                String tmpString = "";
                StringBuilder retJSON = new StringBuilder();
                while ((tmpString = reader.readLine()) != null) {
                    retJSON.append(tmpString + "\n");
                }

                JSONObject jsonObject = new JSONObject(retJSON.toString());
                String code = jsonObject.getString("code");


                if (code.equals("0")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    IP = data.getString("ip") + "(" + data.getString("country")
                            + data.getString("area") + "区"
                            + data.getString("region") + data.getString("city")
                            + data.getString("isp") + ")";

                    Log.e("提示", "您的IP地址是：" + IP);
                } else {
                    IP = "";
                    Log.e("提示", "IP接口异常，无法获取IP地址！");
                }
            } else {
                IP = "";
                Log.e("提示", "网络连接异常，无法获取IP地址！");
            }
        } catch (Exception e) {
            IP = "";
            Log.e("提示", "获取IP地址时出现异常，异常信息是：" + e.toString());
        }
        return IP;
    }


    @Override
    public void run() {

        if( type == UPD_SERVER_HELP) {
            Log.d("UdpHelper", "本机ip地址:" + UdpHelper.getIP());
            StartListen();
        }else if(type == UPD_CLIENT_HELP){
            sBufProcThread();
        }
    }


    class SBuf{
        public byte[] buf;
        public int dataSize;

        public SBuf(byte[] buf,int dataSize){
            this.buf = buf;
            this.dataSize = dataSize;
        }
    }
}
